package cn.wyu.blog;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServlet;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping(value = "/post")
public class blogController extends HttpServlet {

    @Autowired
    private PostDAO postDAO;

    @ModelAttribute("visibility")
    public List<String> getVisibility(){
        ArrayList<String> visibility = new ArrayList<>();
        visibility.add("公开");
        visibility.add("朋友可见");
        visibility.add("仅自己可见");
        return visibility;
    }

    @RequestMapping(value = "/publish",method = RequestMethod.GET)
    public String blog(){
        return "post";
    }

    @RequestMapping(value = "/publish",method = RequestMethod.POST)
    public String save(Post post,Model model){
        String content = post.getContent();
        if(content!=null&&content.length()>0&&content.length()<140){
            //保存博文到数据库
            postDAO.add(post);
            return "redirect:../timeline/my";
        }
        else if(content!=null&&content.length()>140){
            //博文超出长度，显示错误信息
            model.addAttribute("errorMsg","博文内容不能超过140字符");
        }
        return "post";
    }

    @RequestMapping(value = "/remove/{uuid}")
    public String remove(@PathVariable String uuid){
        this.postDAO.remove(uuid);
        return "redirect:/timeline/my";
    }
}
